<?php
/**
 * @package PHPKit.
 * @author: mawenpei
 * @date: 2016/6/14
 * @time: 16:01
 */
namespace HuoCore\Helper;

use Illuminate\Support\Facades\Log;

class NetUtility
{
    /**
     * 获取远程的json格式数据
     *
     * @param $url 远程URL地址
     * @param $params 数组格式的参数
     * @param $method 方法 GET/POST
     * @param bool|false $multi 待上传文件数组
     * @param array $header header
     * @return bool|mixed
     */
    public static function loadJson($url,$params,$method,$multi=false,$header = array())
    {
        $response = self::loadByCurl($url,$params,$method,$multi,$header);
        if($response===false) return $response;
        $response = json_decode($response,true);
        if(json_last_error() !== JSON_ERROR_NONE) return false;
        return $response;
    }

    /**
     * get remote data by curl
     * @param $url
     * @param $params
     * @param $method
     * @param bool|false $multi
     * @param array $header
     * @return bool|mixed
     */
    public static function loadByCurl($url,$params,$method,$multi=false,$header = array())
    {
        Log::info('curl request start:' . $method . ' ' . $url,$params);
        $http_headers = array();
        $method = strtoupper($method);
        $ci = curl_init();
        curl_setopt($ci,CURLOPT_CONNECTTIMEOUT,30);
        curl_setopt($ci,CURLOPT_TIMEOUT,30);
        curl_setopt($ci,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ci,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ci,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ci,CURLOPT_HEADER,false);
        if($method == 'POST'){
            curl_setopt($ci,CURLOPT_POST,true);
            if(is_array($multi)){
                foreach($multi as $key=>$file){
                    $params[$key] = '@' . $file;
                }
            }
            $params = http_build_query($params);
            curl_setopt($ci,CURLOPT_POSTFIELDS,$params);
        }elseif($method == 'GET'){
            if(!empty($params)){
                $url = $url . (strpos($url,'?')!==false ? '&' : '?') . (is_array($params) ? http_build_query($params) : $params );
            }
        }

        curl_setopt($ci,CURLINFO_HEADER_OUT,true);
        curl_setopt($ci,CURLOPT_URL,$url);
        if($http_headers){
            curl_setopt($ci,CURLOPT_HTTPHEADER,$http_headers);
        }
        $response = curl_exec($ci);
        $status_code = curl_getinfo($ci,CURLINFO_HTTP_CODE);
        curl_close($ci);
        Log::info('curl request end:' . $status_code . ' ' . $response);
        if($status_code==200) return $response;
        if($status_code>=500){
            Log::error($response);
        }
        return false;
    }

    public static function parseCookie($header)
    {
        $cookie = [];
        $csplit = explode(';',$header);
        foreach($csplit as $data){
            $cinfo = explode('=',$data);
            $cinfo[0] = trim($cinfo[0]);
            if($cinfo[0] == 'expires') $cinfo[1] = strtotime($cinfo[1]);
            if($cinfo[0] == 'secure') $cinfo[1] = 'true';
            if($cinfo[0] == 'HttpOnly') $cinfo[1] = 'true';
            if(in_array(strtolower($cinfo[0]),['domain','expires','path','secure','comment','httponly'])){
                $cookie[ucfirst($cinfo[0])] = $cinfo[1];
            }else{
                $cookie['Name'] = $cinfo[0];
                $cookie['Value'] = $cinfo[1];
            }
        }
        return $cookie;
    }

    public static function getIp()
    {
        static $realip = NULL;

        if ($realip !== NULL)
        {
            return $realip;
        }

        if (isset($_SERVER))
        {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

                foreach ($arr AS $ip)
                {
                    $ip = trim($ip);

                    if ($ip != 'unknown')
                    {
                        $realip = $ip;

                        break;
                    }
                }
            }
            elseif (isset($_SERVER['HTTP_CLIENT_IP']))
            {
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            }
            else
            {
                if (isset($_SERVER['REMOTE_ADDR']))
                {
                    $realip = $_SERVER['REMOTE_ADDR'];
                }
                else
                {
                    $realip = '0.0.0.0';
                }
            }
        }
        else
        {
            if (getenv('HTTP_X_FORWARDED_FOR'))
            {
                $realip = getenv('HTTP_X_FORWARDED_FOR');
            }
            elseif (getenv('HTTP_CLIENT_IP'))
            {
                $realip = getenv('HTTP_CLIENT_IP');
            }
            else
            {
                $realip = getenv('REMOTE_ADDR');
            }
        }

        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

        return $realip;
    }
}